// @ts-nocheck
import { ResponseData } from '@/api/interface'
import { useState, useEffect } from 'react'
/**
 * 接口数据返回前加载loading
 * @param service 接口函数
 * @param defaultParams 默认参数
 * @param initialData 初始值
 * @returns
 * request: 请求函数
 * refresh: 刷新数据
 * loading: 是否是加载中状态
 * params: 请求参数
 * data: 接口返回值
 */

interface useAsyncParams<T, U> {
  service: (params?: any) => Promise<[any, ResponseData<T> | undefined]>
  defaultParams?: { [key: string]: unknown }
  initialData?: Record<string, unknown> | any[]
  enabled?: boolean
  clearFn?: (data: T) => U
}

export const useAsync = <T, U = T>({
  service,
  defaultParams = {},
  initialData,
  enabled = true,
  clearFn
}: useAsyncParams<T, U>) => {
  const [params, setParams] = useState(defaultParams)
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState<U>(initialData)
  const [err, setErr] = useState<Error | null>(null)

  const request = async _params => {
    if (!enabled) return
    setParams(_params)
    setLoading(true)
    const [err, res] = await service(_params)
    setLoading(false)
    if (err) {
      setErr(err)
    } else {
      setData(clearFn ? clearFn(res.data) : res.data)
    }
  }

  const refresh = () => {
    request(params)
  }

  useEffect(refresh, [])

  return { request, refresh, loading, params, data, err }
}
